<?php

namespace App\Models\Customer;

use App\Helpers\Code;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use App\Models\Basic\RegionProvince;
use Illuminate\Support\Facades\Auth;

class Doctor extends BaseModel
{

    protected $table = 'customer_doctors';
    protected $fillable = [
        'customer_id', 'department_id', 'title', 'code', 'job_title', 'is_monthly', 'salesman', 'phone', 'email', 'alipay',
        'wechat', 'field', 'type', 'intro', 'specialty', 'other', 'region', 'province', 'state', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = [];
    public $params = ['title', 'code', 'customer', 'department', 'phone', 'salesman'];

    public function customer()
    {
        return $this->belongsTo('App\Models\Customer\Customer', 'customer_id');
    }

    public function department()
    {
        return $this->belongsTo('App\Models\Customer\CustomerDepartment', 'department_id');
    }

    public function region()
    {
        return $this->belongsTo('App\Models\Basic\Region', 'region');
    }

    public function province()
    {
        return $this->belongsTo('App\Models\Basic\RegionProvince', 'province');
    }

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function salesman()
    {
        return $this->belongsTo('App\Models\Account\User', 'salesman');
    }

    public function type()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'type', 'code');
    }

    public function field()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'field', 'code');
    }

    public function addDoctor($data)
    {
        //医院/机构-科室/部门关系
        $customer = CustomerDepartment::where('customer_id', $data['customer_id'])->where('id', $data['department_id'])->count();
        if ($customer < 1) {
            return null;
        }

        //大区-省区关系
        $province = RegionProvince::where('region_id', $data['region'])->where('id', $data['province'])->count();
        if ($province < 1) {
            return Code::INSIDE_ERROR;
        }

        //判断客户分类是否存在
        $type = DictionaryMember::whereHas('dictionary', function ($dictionary) {
            $dictionary->where('code', 'khlx');
        })->where('code', $data['type'])->count();
        if ($type < 1) {
            return Code::INSIDE_ERROR_1;
        }

        //判断专业领域是否存在
        if (isset($data['field'])) {
            $type = DictionaryMember::whereHas('dictionary', function ($dictionary) {
                $dictionary->where('code', 'zyly');
            })->where('code', $data['field'])->count();
            if ($type < 1) {
                return Code::INSIDE_ERROR_2;
            }
        }

        //拼接code
        $code = $this->orderBy('code', 'desc')->limit(1)->first(['code']);
        if ($code) {
            $data['code'] = 'NC' . str_pad(substr($code->code,2) + 1, 4, 0, STR_PAD_LEFT);
        } else {
            $data['code'] = 'NC0001';
        }
        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑医生
     * @param $data
     * @param $id
     * @return int|null
     */
    public function editDoctor($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        //大区与省区关系
        $region = $data['region'] ?? $model->region;
        $province = $data['province'] ?? $model->province;
        $provinceCheck = RegionProvince::where('region_id', $region)->where('id', $province)->count();
        if ($provinceCheck < 1) {
            return Code::INSIDE_ERROR;
        }

        //医院-科室关系
        $customer = $data['customer_id'] ?? $model->customer_id;
        $department = $data['department_id'] ?? $model->department_id;
        $customerCheck = CustomerDepartment::where('customer_id', $customer)->where('id', $department)->count();
        if ($customerCheck < 1) {
            return Code::INSIDE_ERROR_1;
        }

        //判断客户分类是否存在
        $type = DictionaryMember::whereHas('dictionary', function ($dictionary) {
            $dictionary->where('code', 'khlx');
        })->where('code', $data['type'])->count();
        if ($type < 1) {
            return Code::INSIDE_ERROR_2;
        }

        //判断专业领域是否存在
        if (isset($data['field'])) {
            $type = DictionaryMember::whereHas('dictionary', function ($dictionary) {
                $dictionary->where('code', 'zyly');
            })->where('code', $data['field'])->count();
            if ($type < 1) {
                return Code::INSIDE_ERROR_3;
            }
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取医生全部
     * @param $keyword
     * @return mixed
     */
    public function getDoctorTree($limit, $sorter, $keyword, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }
        $model->select(['id', 'customer_id', 'department_id', 'title', 'code'])->where('state', 1);

        if (isset($keyword)) {
            $model->where('code', 'like', '%' . $keyword . '%')->orWhere('title', 'like', '%' . $keyword . '%');
        }

        $model->with(['customer' => function($customer) {
            $customer->where('state', 1)->select(['id', 'title', 'code']);
        }, 'department' => function($department) {
            $department->where('state', 1)->select(['id', 'title', 'code']);
        }]);

        return $model->paginate($perPage)->toArray();
    }

    /**
     * 获取医生详情
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getDoctor($id)
    {
        $model = $this->with([
            'customer:id,title,code',
            'department:id,title,code',
            'region:id,title',
            'province:id,title',
            'createdBy:id,username',
            'salesman:id,username',
            'type:code,title',
            'field:code,title'
        ])->find($id, ['customer_id', 'department_id', 'title', 'code', 'job_title', 'is_monthly', 'salesman', 'phone', 'email', 'alipay',
            'wechat', 'field', 'type', 'intro', 'specialty', 'other', 'region', 'province', 'state', 'created_by']);

        if (!$model) {
            return null;
        }

        return $model;
    }

    /**
     * 获取医生列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getDoctorList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'customer_id', 'department_id', 'title', 'code', 'job_title', 'is_monthly', 'salesman', 'phone', 'email', 'alipay',
            'wechat', 'field', 'type', 'intro', 'specialty', 'other', 'region', 'province', 'state', 'created_by'])
            ->with([
                'customer:id,title,code',
                'department:id,title,code',
                'region:id,title',
                'province:id,title',
                'createdBy:id,username',
                'salesman:id,username',
                'type:title,code',
                'field:code,title'
            ]);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                case 'phone':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
                case 'customer':
                    $model->whereHas('customer', function($customer) use ($value) {
                        $customer->where(function($where) use($value) {
                            $where->where('title', 'like', '%' . $value . '%')->orWhere('Code', 'like', '%' . $value . '%');
                        });
                    });
                    break;
                case 'department':
                    $model->whereHas('department', function($department) use ($value) {
                        $department->where(function($where) use($value) {
                            $where->where('title', 'like', '%' . $value . '%')->orWhere('Code', 'like', '%' . $value . '%');
                        });
                    });
                    break;
                case 'salesman':
                    $model->whereHas('salesman', function($salesman) use ($value) {
                        $salesman->where('username', $value);
                    });
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }
}
